package com.nidu.demo.web.config;

import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.GroupedOpenApi;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;

@Configuration
@EnableConfigurationProperties({SwaggerProperties.class, WebProperties.class})
@RequiredArgsConstructor
public class SwaggerAutoConfiguration {

    private final WebProperties webProperties;
    private final SwaggerProperties properties;

    /**
     * 全局 OpenAPI 配置
     */
    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
                .info(new Info()
                        .title(properties.getTitle())
                        .description(properties.getRemark())
                        .version(properties.getVersion())
                        .contact(new Contact().name(properties.getAuthor()).url(properties.getUrl()).email(properties.getEmail()))
                        .license(new License().name(properties.getLicense()).url(properties.getLicenseUrl())))
                .components(new Components().addSecuritySchemes(HttpHeaders.AUTHORIZATION, new SecurityScheme()
                        .type(SecurityScheme.Type.APIKEY)
                        .name(HttpHeaders.AUTHORIZATION)
                        .in(SecurityScheme.In.HEADER)))
                // 添加 SecurityRequirement，Swagger UI 才会自动带上 Authorization
                .addSecurityItem(new SecurityRequirement().addList(HttpHeaders.AUTHORIZATION));
    }

    /**
     * 管理后台 API 组
     */
    @Bean
    public GroupedOpenApi adminApi() {
        return GroupedOpenApi.builder()
                .group("管理后台接口")
                .packagesToScan(webProperties.getBasePackage())
                .pathsToMatch(webProperties.getAdminApi().getPrefix() + "/**")
                .build();
    }

    /**
     * 移动端 API 组
     */
    @Bean
    public GroupedOpenApi appApi() {
        return GroupedOpenApi.builder()
                .group("移动端接口")
                .packagesToScan(webProperties.getBasePackage())
                .pathsToMatch(webProperties.getAppApi().getPrefix() + "/**")
                .build();
    }

}
